const  fs = require('fs'), 
    https = require('https'), 
     http = require('http'),
httpProxy = require('http-proxy'), 
     path = require('path'),
	  url = require("url"),
 mockBSOI = require("./mock/bsoi.js");

const mimeTypes = {
	"html" : "text/html",
	"jpeg" : "image/jpeg",
	"jpg" : "image/jpeg",
	"png" : "image/png",
	"js" : "text/javascript",
	"css" : "text/css"
};

var options = {
	https : {
		key : fs.readFileSync('server/privatekey.pem', 'utf8'),
		cert : fs.readFileSync('server/certificate.pem', 'utf8')
	},
	host : null,
	appName : '/',
	src : '/'
};

module.exports.run = function(config) {
	options.host = config.host;
	options.appName = config.appName;
	options.src = config.src;
	options.serverName = config.host.serverName;
	this.createServer();
	
	mockBSOI.run(config.country);
};

module.exports.createServer = function() {

	var proxy = new httpProxy.HttpProxy({
	  target: options.host,
      changeOrigin:true
	});
    proxy.on('proxyResponse', function(req, res, response) {
        var cookies = response.headers['set-cookie'];
        var index = -1;
        if (cookies) {
            for (var key in cookies) {
                index = cookies[key].indexOf('Secure');
                if (index != -1) {
                    cookies[key] = cookies[key].substring(0, index-1);
                }
            }
        }
    });
	
	//var proxy = new httpProxy.RoutingProxy();
	https.createServer(options.https, function(req, res) {
		res.writeHead(200);
		if (req.url.indexOf(options.serverName) >= 0) {
			//proxy.proxyRequest(req, res, options.host);
			proxy.proxyRequest(req, res);
		} else {
			staticFileHandler(req, res);
		}
	}).listen(8443);

	http.createServer(function(req, res) {
		if (req.url.indexOf(options.serverName) >= 0) {
			//proxy.proxyRequest(req, res, options.host);
			proxy.proxyRequest(req, res);
		} else {
			staticFileHandler(req, res);
		}
	}).listen(8000);

	var staticFileHandler = function(req, res) {
		var uri = url.parse(req.url).pathname;
		if(uri === '/'+options.appName){
			uri = uri.replace(options.appName, '');
		}
		var t_projectSrcPath = [ process.cwd(),  options.src, unescape(uri) ].join('/');
		var filename = path.join(t_projectSrcPath);

		var stats;
		try {
			stats = fs.lstatSync(filename); // throws if path doesn't exist
		} catch (e) {
			res.writeHead(404, {
				'Content-Type' : 'text/plain'
			});
			res.write('404 Not Found\n');
			res.end();
			return;
		}

		if (stats.isFile()) {
			// path exists, is a file
			var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
			res.writeHead(200, {
				'Content-Type' : mimeType
			});

			var fileStream = fs.createReadStream(filename);
			fileStream.pipe(res);
		} else if (stats.isDirectory()) {
			var fileStream = fs.createReadStream(filename + '/index.html');
			fileStream.pipe(res);
		} else {
			// Symbolic link, other?
			// TODO: follow symlinks? security?
			res.writeHead(500, {
				'Content-Type' : 'text/plain'
			});
			res.write('500 Internal server error\n');
			res.end();
		}
	};

};
